package org.testis.utils.middleware;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.orm.PersistentException;
import org.orm.PersistentTransaction;
import org.testis.orm.classes.T_test_dataobjectpairs;
import org.testis.orm.classes.T_test_dataobjectpairsCriteria;
import org.testis.orm.classes.T_test_profiledetails;
import org.testis.orm.classes.T_test_profiledetailsCriteria;
import org.testis.orm.classes.T_test_profilekeys;
import org.testis.orm.classes.T_test_profilekeysCriteria;
import org.testis.orm.classes.T_test_profilekeysFactory;
import org.testis.orm.classes.T_test_profiles;
import org.testis.orm.classes.T_test_profilesCriteria;
import org.testis.orm.classes.T_test_profilesFactory;

/**
 * 
 * @author nurhat
 */
public class GlobalDataHandler extends DbConnectionSupplier {

    public HashMap getProfileKeysAsMap() {
	return profileKeyListToMap(getProfileKeys());
    }

    public List<String> getProfileKeysGroupNames() {
	List<String> groupNames = new ArrayList<String>();
	T_test_profilekeys[] keys = null;
	try {
	    keys = T_test_profilekeysFactory.listT_test_profilekeysByQuery(
		    null, null);

	} catch (PersistentException ex) {
	}
	if (keys == null) {
	    return groupNames;
	}
	for (int i = 0; i < keys.length; i++) {
	    String tmp = keys[i].getGroupname();
	    if (!groupNames.contains(tmp)) {
		groupNames.add(tmp);
	    }
	}
	return groupNames;

    }

    public List<String[]> getProfileKeysAsArray() {
	T_test_profilekeys[] keys = getProfileKeys();
	List<String[]> lst = new LinkedList<String[]>();
	for (int i = 0; i < keys.length; i++) {
	    String[] keyVal = new String[4];
	    keyVal[0] = Integer.toString(keys[i].getId());
	    keyVal[1] = keys[i].getName();
	    keyVal[2] = keys[i].getGroupname();
	    keyVal[3] = keys[i].getPriority();
	    lst.add(keyVal);
	}
	return lst;
    }

    public List<String[]> getProfileKeyDetailsAsArray(int profileId) {
	T_test_profiledetails[] details = getProfileDetailsById(profileId);
	List<String[]> lst = new LinkedList<String[]>();
	for (int i = 0; i < details.length; i++) {
	    String[] keyVal = new String[4];
	    T_test_profilekeys profileKey = getProfileKeyById(details[i]
		    .getKeyId());
	    keyVal[0] = profileKey.getName();
	    keyVal[1] = details[i].getValue();
	    keyVal[2] = profileKey.getGroupname();
	    keyVal[3] = profileKey.getPriority();
	    lst.add(keyVal);
	}
	return lst;
    }

    public HashMap getProfilesAsMap() {
	return profilesListToMap(getProfiles());
    }

    public HashMap getProfileDetailsAsMap(int profileId) {
	return profileDetailsToMap(getProfileDetailsById(profileId));

    }

    private HashMap profileDetailsToMap(T_test_profiledetails[] list) {
	HashMap hp = new HashMap();
	if (list != null) {
	    for (int i = 0; i < list.length; i++) {
		T_test_profiledetails tmp = list[i];
		hp.put(getProfileKeyById(tmp.getKeyId()).getName(),
			tmp.getValue());
	    }
	}
	return HashMapUtils.sortHashMapByKeys(hp);
    }

    private HashMap profileKeyListToMap(T_test_profilekeys[] list) {
	HashMap hp = new HashMap();
	if (list != null) {
	    for (int i = 0; i < list.length; i++) {
		T_test_profilekeys tmp = list[i];
		hp.put(tmp.getId(), tmp.getName());
	    }
	}
	return HashMapUtils.sortHashMapByValues(hp);
    }

    private HashMap profilesListToMap(T_test_profiles[] list) {
	HashMap hp = new HashMap();
	if (list != null) {
	    for (int i = 0; i < list.length; i++) {
		T_test_profiles tmp = list[i];
		hp.put(tmp.getId(), tmp.getName());
	    }
	}
	return HashMapUtils.sortHashMapByValues(hp);
    }

    public boolean removeProfile(int profileId) {
	boolean result = false;
	if (removeProfileDetailByProfileId(profileId)) {
	    try {

		PersistentTransaction t = openDBConnection().beginTransaction();
		try {

		    T_test_profilesCriteria criteria = new T_test_profilesCriteria();
		    criteria.id.eq(profileId);
		    T_test_profiles obj = criteria.uniqueT_test_profiles();
		    if (obj != null) {
			obj.delete();
		    }
		    t.commit();
		    result = true;

		} catch (PersistentException ex) {
		    t.rollback();
		} finally {
		    closeDBConnection();
		}
	    } catch (PersistentException ex) {
	    }
	}
	return result;
    }

    public boolean removeProfileKey(String keyName) {
	boolean result = false;
	if (removeProfileKeyFromDetail(keyName)) {
	    try {

		PersistentTransaction t = openDBConnection().beginTransaction();
		try {

		    T_test_profilekeysCriteria criteria = new T_test_profilekeysCriteria();
		    criteria.name.eq(keyName);
		    T_test_profilekeys obj = criteria
			    .uniqueT_test_profilekeys();
		    if (obj != null) {
			obj.delete();
		    }
		    t.commit();
		    result = true;

		} catch (PersistentException ex) {
		    t.rollback();
		} finally {
		    closeDBConnection();
		}
	    } catch (PersistentException ex) {
	    }
	}
	return result;
    }

    public boolean removeProfileKey(int keyId) {
	boolean result = false;
	if (removeProfileKeyFromDetail(keyId)) {
	    try {
		PersistentTransaction t = openDBConnection().beginTransaction();
		try {
		    T_test_profilekeysCriteria criteria = new T_test_profilekeysCriteria();
		    criteria.id.eq(keyId);
		    T_test_profilekeys obj = criteria
			    .uniqueT_test_profilekeys();
		    if (obj != null) {
			obj.delete();
		    }
		    t.commit();
		    result = true;

		} catch (PersistentException ex) {
		    ex.printStackTrace();
		    t.rollback();
		} finally {
		    closeDBConnection();
		}
	    } catch (PersistentException ex) {
		ex.printStackTrace();
	    }
	}
	return result;
    }

    public boolean removeProfileDetailByProfileId(int profileId) {
	boolean result = false;
	try {

	    PersistentTransaction t = openDBConnection().beginTransaction();
	    T_test_profiles profile = getProfileById(profileId);
	    if (profile == null) {
		t.rollback();
		return false;
	    }
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();

		T_test_profilesCriteria proCriteria = criteria
			.createProfileCriteria();
		proCriteria.id.eq(profileId);
		T_test_profiledetails[] obj = criteria
			.listT_test_profiledetails();
		if (obj != null) {
		    for (int i = 0; i < obj.length; i++) {
			T_test_profiledetails t_test_profiledetails = obj[i];
			t_test_profiledetails.deleteAndDissociate();
		    }
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeProfileDetail(int id) {
	boolean result = false;
	try {

	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
		criteria.id.eq(id);
		T_test_profiledetails obj = criteria
			.uniqueT_test_profiledetails();
		if (obj != null) {
		    obj.deleteAndDissociate();
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeProfileKeyFromDetail(String keyName) {
	boolean result = false;
	try {
	    T_test_profilekeys key = getProfileKeyByName(keyName);
	    if (key == null) {
		return false;
	    }
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();

		criteria.keyId.eq(key.getId());

		T_test_profiledetails[] obj = criteria
			.listT_test_profiledetails();
		if (obj != null) {
		    for (int i = 0; i < obj.length; i++) {
			T_test_profiledetails t_test_profiledetails = obj[i];
			t_test_profiledetails.deleteAndDissociate();
		    }
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeProfileKeyFromDetail(int keyId) {
	boolean result = false;
	try {
	    T_test_profilekeys key = getProfileKeyById(keyId);
	    if (key == null) {
		return false;
	    }
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();

		criteria.keyId.eq(key.getId());
		T_test_profiledetails[] obj = criteria
			.listT_test_profiledetails();
		if (obj != null) {
		    for (int i = 0; i < obj.length; i++) {
			T_test_profiledetails t_test_profiledetails = obj[i];
			t_test_profiledetails.deleteAndDissociate();
		    }
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeProfileDetail(int profileId, int keyId) {
	boolean result = false;
	try {
	    T_test_profiles profile = getProfileById(profileId);
	    T_test_profilekeys key = getProfileKeyById(keyId);
	    if (profile == null || key == null) {
		return false;
	    }
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();

		T_test_profilesCriteria proCriteria = criteria
			.createProfileCriteria();
		proCriteria.id.eq(profileId);
		criteria.keyId.eq(key.getId());

		T_test_profiledetails obj = criteria
			.uniqueT_test_profiledetails();
		if (obj != null) {
		    obj.deleteAndDissociate();
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeProfileDetail(int profileId, String keyName) {
	boolean result = false;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    T_test_profiles profile = getProfileById(profileId);
	    T_test_profilekeys key = getProfileKeyByName(keyName);
	    if (profile == null || key == null) {
		t.rollback();
		return false;
	    }
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();

		T_test_profilesCriteria proCriteria = criteria
			.createProfileCriteria();
		proCriteria.id.eq(profileId);
		criteria.keyId.eq(key.getId());
		T_test_profiledetails obj = criteria
			.uniqueT_test_profiledetails();
		if (obj != null) {
		    obj.deleteAndDissociate();
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeProfileDetail(int[] profileIdList, String keyName) {
	boolean result = false;
	if (profileIdList == null) {
	    return false;
	}

	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();

	    T_test_profilekeys profilekey = getProfileKeyByName(keyName);
	    if (profilekey == null) {
		return false;
	    }

	    try {
		for (int i = 0; i < profileIdList.length; i++) {
		    int profileId = profileIdList[i];
		    T_test_profiles profile = getProfileById(profileId);
		    if (profile == null) {
			continue;
		    }
		    T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
		    criteria.createProfileCriteria().id.eq(profileId);
		    criteria.keyId.eq(profilekey.getId());
		    T_test_profiledetails profiledetail = criteria
			    .uniqueT_test_profiledetails();
		    if (profiledetail != null) {
			profiledetail.deleteAndDissociate();
		    }
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    protected boolean saveProfileDetailWithNoTransaction(int profileId,
	    String keyName, String value) {
	boolean result = false;
	T_test_profiles profile = getProfileById(profileId);
	T_test_profilekeys key = getProfileKeyByName(keyName);
	if (profile == null || key == null) {
	    return false;
	}
	try {
	    T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();

	    T_test_profilesCriteria proCriteria = criteria
		    .createProfileCriteria();
	    proCriteria.id.eq(profileId);
	    criteria.keyId.eq(key.getId());

	    T_test_profiledetails obj = criteria.uniqueT_test_profiledetails();
	    if (obj == null) {
		obj = new T_test_profiledetails();
		obj.setKeyId(key.getId());
		obj.setProfile(profile);
	    }
	    obj.setValue(value);
	    obj.save();
	    result = true;
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	} finally {
	}
	return result;
    }

    public boolean saveProfileDetail(int profileId, String key, String value) {
	boolean result = false;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();

	    T_test_profiles profile = getProfileById(profileId);
	    T_test_profilekeys profileKey = getProfileKeyByName(key);
	    if (profile == null || profileKey == null) {
		return false;
	    }

	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
		criteria.createProfileCriteria().id.eq(profileId);
		criteria.keyId.eq(profileKey.getId());
		T_test_profiledetails profiledetail = criteria
			.uniqueT_test_profiledetails();

		if (profiledetail == null) {
		    profiledetail = new T_test_profiledetails();
		    profiledetail.setKeyId(profileKey.getId());
		    profiledetail.setProfile(profile);
		}
		profiledetail.setValue(value);
		profiledetail.save();
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		ex.printStackTrace();
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return result;
    }

    public boolean saveProfileDetail(int[] profileIdList, String key,
	    String value) {
	boolean result = false;
	if (profileIdList == null) {
	    return false;
	}

	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();

	    T_test_profilekeys profileKey = getProfileKeyByName(key);
	    if (profileKey == null) {
		return false;
	    }

	    try {
		for (int i = 0; i < profileIdList.length; i++) {
		    int profileId = profileIdList[i];
		    T_test_profiles profile = getProfileById(profileId);
		    if (profile == null) {
			continue;
		    }
		    T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
		    criteria.createProfileCriteria().id.eq(profileId);
		    criteria.keyId.eq(profileKey.getId());
		    T_test_profiledetails profiledetail = criteria
			    .uniqueT_test_profiledetails();
		    if (profiledetail == null) {
			profiledetail = new T_test_profiledetails();
			profiledetail.setKeyId(profileKey.getId());
			profiledetail.setProfile(profile);
		    }
		    profiledetail.setValue(value);
		    profiledetail.save();
		}
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		ex.printStackTrace();
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return result;
    }

    public boolean saveProfileDetail(int id, int profileId, int keyId,
	    String value) {
	boolean result = false;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    T_test_profiles profile = getProfileById(profileId);
	    T_test_profilekeys profilekey = getProfileKeyById(keyId);
	    try {
		T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
		if (id != 0) {
		    criteria.id.eq(id);
		} else {
		    criteria.createProfileCriteria().id.eq(profileId);
		    criteria.keyId.eq(keyId);
		}
		T_test_profiledetails profiledetail = criteria
			.uniqueT_test_profiledetails();
		if (profiledetail == null) {
		    profiledetail = new T_test_profiledetails();
		    profiledetail.setKeyId(profilekey.getId());
		    profiledetail.setProfile(profile);
		}
		profiledetail.setValue(value);
		profiledetail.save();
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public T_test_profiledetails[] getProfileDetailsById(int profileId) {
	T_test_profiledetails[] result = null;
	try {
	    T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
	    T_test_profilesCriteria proCriteria = criteria
		    .createProfileCriteria();
	    proCriteria.id.eq(profileId);
	    result = criteria.listT_test_profiledetails();
	} catch (PersistentException ex) {
	}
	return result;
    }

    public String getProfileDetailValue(int profileId, String keyName) {
	T_test_profiledetails result = null;
	try {
	    T_test_profilekeys key = getProfileKeyByName(keyName);
	    T_test_profiledetailsCriteria criteria = new T_test_profiledetailsCriteria();
	    T_test_profilesCriteria proCriteria = criteria
		    .createProfileCriteria();
	    proCriteria.id.eq(profileId);
	    criteria.keyId.eq(key.getId());
	    result = criteria.uniqueT_test_profiledetails();
	} catch (PersistentException ex) {
	}
	if (result != null) {
	    return result.getValue();
	}
	return "";
    }

    public T_test_profiles[] getProfiles() {
	T_test_profiles[] result = null;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		result = T_test_profilesFactory.listT_test_profilesByQuery(
			null, null);

	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public T_test_profiles getProfileById(int profileId) {
	T_test_profiles result = null;

	try {
	    T_test_profilesCriteria criteria = new T_test_profilesCriteria();
	    criteria.id.eq(profileId);
	    result = criteria.uniqueT_test_profiles();

	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean saveProfile(int id, String name) {
	boolean result = false;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profilesCriteria criteria = new T_test_profilesCriteria();
		T_test_profiles obj = null;
		if (id != 0) {
		    criteria.id.eq(id);
		    obj = criteria.uniqueT_test_profiles();
		}
		if (obj == null) {
		    obj = new T_test_profiles();
		}
		obj.setName(name);
		obj.save();
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public int createCopyOfProfile(int copyId) {
	int result = 0;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profiles profile = getProfileById(copyId);
		String newName = "Copy of " + profile.getName();
		T_test_profiles obj = null;
		obj = new T_test_profiles();
		obj.setName(newName);
		obj.save();
		HashMap hmap = getProfileDetailsAsMap(copyId);
		Iterator iter = hmap.entrySet().iterator();
		while (iter.hasNext()) {
		    Map.Entry entry = (Map.Entry) iter.next();
		    saveProfileDetailWithNoTransaction(obj.getId(), entry
			    .getKey().toString(), entry.getValue().toString());
		}
		t.commit();
		result = obj.getId();
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public int saveProfile(String name) {
	int result = 0;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profilesCriteria criteria = new T_test_profilesCriteria();
		T_test_profiles obj = null;

		obj = new T_test_profiles();
		obj.setName(name);
		obj.save();
		t.commit();
		result = obj.getId();
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public T_test_profilekeys getProfileKeyByName(String keyName) {
	T_test_profilekeys result = null;

	try {
	    T_test_profilekeysCriteria criteria = new T_test_profilekeysCriteria();
	    criteria.name.eq(keyName);
	    result = criteria.uniqueT_test_profilekeys();
	} catch (PersistentException ex) {
	}

	return result;
    }

    public T_test_profilekeys getProfileKeyById(int keyId) {
	T_test_profilekeys result = null;
	try {
	    T_test_profilekeysCriteria criteria = new T_test_profilekeysCriteria();
	    criteria.id.eq(keyId);
	    result = criteria.uniqueT_test_profilekeys();

	} catch (PersistentException ex) {
	}

	return result;
    }

    public T_test_profilekeys[] getProfileKeys() {
	T_test_profilekeys[] result = null;
	try {
	    result = T_test_profilekeysFactory.listT_test_profilekeysByQuery(
		    null, null);

	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean saveProfileKey(int id, String name, String groupname,
	    String priority) {

	boolean result = false;
	if (groupname.trim().equals("")) {
	    groupname = "NONE";
	}
	if (priority.trim().equals("")) {
	    priority = "P5";
	}
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_test_profilekeysCriteria criteria = new T_test_profilekeysCriteria();
		if (id != 0) {
		    criteria.id.eq(id);
		} else {
		    criteria.name.eq(name);
		}
		T_test_profilekeys obj = criteria.uniqueT_test_profilekeys();
		String oldName;
		String newName;
		if (obj == null) {
		    obj = new T_test_profilekeys();
		} else {
		    oldName = obj.getName();
		    oldName = "@GLOBAL_" + oldName + "@";
		    newName = "@GLOBAL_" + name + "@";
		    T_test_dataobjectpairsCriteria crit = new T_test_dataobjectpairsCriteria();
		    crit.value.like("%" + oldName + "%");
		    T_test_dataobjectpairs[] pairs = crit
			    .listT_test_dataobjectpairs();
		    for (int i = 0; i < pairs.length; i++) {
			String oldValue = pairs[i].getValue();
			String newValue = oldValue.replace(oldName, newName);
			pairs[i].setValue(newValue);
			pairs[i].save();
		    }
		}
		obj.setName(name);
		obj.setGroupname(groupname);
		obj.setPriority(priority);
		obj.save();
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }
}
